package org.wanho.servlet;

import org.wanho.util.CookieUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author：汤小洋
 * Date：2023-04-24 10:46
 * Description：<描述>
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");

        // 判断验证码
        String randCode = (String) req.getSession().getAttribute("randCode");
        if (!randCode.equalsIgnoreCase(code)){
            req.setAttribute("errorMsg","验证码不正确！");
            req.getRequestDispatcher("test05.jsp").forward(req,resp);
            return;
        }

        if("admin".equals(username) && "123".equals(password)){
            CookieUtil.addCookie("username",username,600,resp);
            CookieUtil.addCookie("password",password,600,resp);

            // 将用户信息存储到Session中
            req.getSession().setAttribute("username",username);

            req.getRequestDispatcher("/WEB-INF/pages/main.jsp").forward(req,resp);
        }else{
            req.setAttribute("errorMsg","用户名或密码不正确！");
            req.getRequestDispatcher("test05.jsp").forward(req,resp);
        }
    }
}
